package org.wx.herostory.services.processor;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.wx.herostory.services.encoder.CmdHandlerFactory;
import org.wx.herostory.services.encoder.ICmdHandler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 单线程池处理器
 * @author: wangxun
 * @createDate: 2021/3/3
 * @version: 1.0
 */
@Slf4j
public class MainMsgProcessor {
    static private final MainMsgProcessor _instance = new MainMsgProcessor();

    /**
     * 私有构造器
     */
    private MainMsgProcessor() {
    }
    // 单线程的线程池，传入自定义的线程工厂，线程工厂返回MainMsgProcessor名称的线程
    private final ExecutorService _es = Executors.newSingleThreadExecutor((newRunnable)->{
        Thread newThread = new Thread(newRunnable);
        //设置线程名称
        newThread.setName("MainMsgProcessor");
        return newThread;
    });

    static public MainMsgProcessor getInstance(){
        return _instance;
    }

    public void process(ChannelHandlerContext ctx,Object msg){
        if (null == ctx ||
                null == msg) {
            return;
        }

        log.info(
                "收到客户端消息, msgClazz = {}, msgBody = {}",
                msg.getClass().getSimpleName(),
                msg
        );
        // 将任务添加到线程池中，用单个线程的线程池串行执行
        // 如果单线程正在执行任务，那么就将任务发到LinkedBlockingQueue中，等待take取出执行，保证线程安全
        // 攻击的时候不会发生数据丢失，不会产生死锁的现象
        _es.submit(()->{
            try {
                ICmdHandler<? extends GeneratedMessageV3> handler = CmdHandlerFactory.create(msg.getClass());
                handler.handle(ctx,cast(msg));
            } catch (Exception ex) {
                // 记录错误日志
                log.error(ex.getMessage(), ex);
            }
        });


    }

    /**
     * 执行具体的任务
     * @param runnable
     */
    public void process(Runnable runnable){
        if(null == runnable){
            return;
        }
        _es.submit(runnable);
    }


    /**
     * 对象类型转换
     * @param object
     * @param <TCmd>
     * @return
     */
    static private <TCmd extends GeneratedMessageV3> TCmd cast(Object object){
        if (null == object){
            return null;
        }else {
            return (TCmd)object;
        }

    }
}
